package com.neoCalf.neoCommon.utils;

import com.neoCalf.neoCommon.enums.MessageTypeEnum;
import com.neoCalf.neoCommon.enums.UserContactTypeEnum;
import com.neoCalf.neoCommon.model.dto.JoinGroupDto;
import com.neoCalf.neoCommon.model.dto.SendMessageDto;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.redisson.config.Config;


/**
 * @author 小牛
 * @version 1.0
 * @description TODO
 * @date 2025/4/18 11:01
 */
@Slf4j
public class SendUtils {
    private static final String MESSAGE_TOPIC = "message.topic";
    private static final String JOIN_GROUP_TOPIC = "join.group.topic";
    private static final String redisLocal = "127.0.0.1";
    private static final int redisPort = 6379;
    private RedissonClient redissonClient;

    /**
     * 创建连接redis的客户端对象【后续将消息发送给redis 再有redis分发其他设备，解决分布式服务和发现】
     */
    public SendUtils() {
        try {
            Config config = new Config();
            config.useSingleServer().setAddress("redis://" + redisLocal + ":" + redisPort);
            redissonClient = Redisson.create(config);
        } catch (Exception e) {
            log.error("----------初始化redis客户端失败----------\n", e);
        }
    }

    public <T> void sendMessage(SendMessageDto<T> sendMessageDto) {
        try {
            RTopic topic = redissonClient.getTopic(MESSAGE_TOPIC);
            topic.publish(sendMessageDto);
        } catch (Exception e) {
            log.error("消息发送至redis失败", e);
        }
    }

    public void FORCE_OFF_LINE(String userId) {
        SendMessageDto<Object> sendMessageDto = new SendMessageDto<>();
        sendMessageDto.setContactId(userId);
        sendMessageDto.setContactType(UserContactTypeEnum.USER.getType());
        sendMessageDto.setMessageType(MessageTypeEnum.FORCE_OFF_LINE.getType());
        sendMessage(sendMessageDto);
    }

    public void JOIN_GROUP(String groupId, String userId) {
        try {
            JoinGroupDto joinGroupDto = new JoinGroupDto(groupId, userId);
            RTopic topic = redissonClient.getTopic(JOIN_GROUP_TOPIC);
            topic.publish(joinGroupDto);
        } catch (Exception e) {
            log.error("消息发送至redis失败", e);
        }
    }

    public <T> void ListenerMessage(Class<T> var1, MessageListener<? extends T> var2) {
        RTopic topic = redissonClient.getTopic(MESSAGE_TOPIC);
        topic.addListener(var1, var2);
    }

    public <T> void ListenerJoinGroup(Class<T> var1, MessageListener<? extends T> var2) {
        RTopic topic = redissonClient.getTopic(JOIN_GROUP_TOPIC);
        topic.addListener(var1, var2);
    }
}
